<template>
  <view class="root">
    <view class="root-inner" v-if="!visibleCamera">
      <view class="bg-top"></view>
      <view class="container-wrapper">
        <yy-steps v-model="active" :text-style="{fontSize: '24rpx'}" :stepList="stepList"></yy-steps>
        <view class="container-inner">

          <view class="form-style-wrapper">
            <uni-forms ref="formRef" :model="form" validateTrigger="blur" :border="true" err-show-type="toast"
              label-width="95">
              <view class="content-inner-wrapper" v-show="active == 0">
                <view class="form-item-title">场所信息</view>
                <uni-forms-item label="行业分类" name="industryInformationId" required key="industryInformationId">
                  <view class="form-content-item" @click="handleSelectIndustry">
                    <view :class="form.industryInformationId_text ? 'long-select-value' : 'long-select-value-empty'">
                      {{form.industryInformationId_text ? form.industryInformationId_text : '请选择企业所属行业分类'}}
                    </view>
                    <uni-icons type="right" size="21" color="#C2C0C0"></uni-icons>
                  </view>
                </uni-forms-item>
                <uni-forms-item label="场所名称" name="companyName" required key="companyName">
                  <view class="form-content-item" :class="form.companyName ?  '' : 'input-item'">
                    <uni-easyinput type="text" v-model="form.companyName" :inputBorder="false" placeholder="请填写"
                      :clearable="true" />
                  </view>
                </uni-forms-item>
                <uni-forms-item label="开业时间" name="openingTime" required key="openingTime">
                  <view class="form-content-item">
                    <uni-datetime-picker v-model="form.openingTime" type="date" :hide-second="true">
                      <uni-easyinput type="text" v-model="form.openingTime" :inputBorder="false" placeholder="请选择"
                        disabled :clearable="true" />
                    </uni-datetime-picker>
                    <view slot="right" class="map-img">
                      <image :src="baseImgUrl + 'day-icon2.png'" style="width: 30rpx;height: 30rpx;"></image>
                    </view>
                  </view>
                </uni-forms-item>
                <uni-forms-item label="经纬度" name="lnglat_text" required key="lnglat_text">
                  <view class="form-content-item" @click="mapHandle">
                    <uni-easyinput type="text" v-model="form.lnglat_text" :inputBorder="false" disabled
                      disableColor="#ffffff" placeholder="请选择" :clearable="false">
                    </uni-easyinput>
                    <view slot="right" class="map-img">
                      <image :src="baseImgUrl + 'map-icon.png'"></image>
                    </view>
                  </view>
                </uni-forms-item>
                <uni-forms-item label="所属派出所" name="policeAgencyName" required key="policeAgencyName">
                  <view class="form-content-item" @click="policeAgencyFoces">
                    <view :class="form.policeAgencyName ? 'long-select-value' : 'long-select-value-empty'">
                      {{form.policeAgencyName ? form.policeAgencyName : '请选择'}}
                    </view>
                    <uni-icons type="right" size="21" color="#C2C0C0"></uni-icons>
                  </view>
                </uni-forms-item>
                <uni-forms-item label="关联标准地址" name="standardAddress" required key="standardAddress">
                  <view class="form-content-item" @click="getDetailAddress">
                    <view :class="form.standardAddress ? 'long-select-value' : 'long-select-value-empty'">
                      {{form.standardAddress ? form.standardAddress : '请选择'}}
                    </view>
                    <uni-icons type="right" size="21" color="#C2C0C0"></uni-icons>
                  </view>
                </uni-forms-item>
                <view class="image-form-item">
                  <uni-forms-item label="场所门头照片" name="doorheadUrlList" required label-width="100%">
                    <u-upload :fileList="form.doorheadUrlList" @afterRead="(info) => afterReadFive(info, 'form', 18)"
                      @delete="(info) => deletePhoto(info, 'form')" name="doorheadUrlList" :maxCount="1"
                      :multiple="true" width="100" height="80">
                      <image :src="baseImgUrl + 'upload-icon3.png'" style="width: 200rpx; height: 160rpx"></image>
                    </u-upload>
                  </uni-forms-item>
                </view>
                <view class="image-form-item-no-border">
                  <uni-forms-item label="场所内部照片 (请上传1~9张照片)" name="interiorUrlList" required label-width="100%">
                    <u-upload :fileList="form.interiorUrlList" @afterRead="(info) => afterReadFive(info, 'form', 20)"
                      @delete="(info) => deletePhoto(info, 'form')" name="interiorUrlList" :maxCount="9"
                      :multiple="true" width="100" height="80">
                      <image :src="baseImgUrl + 'upload-icon3.png'" style="width: 200rpx; height: 160rpx"></image>
                    </u-upload>
                  </uni-forms-item>
                </view>
                <view class="image-form-item-no-border">
                  <uni-forms-item label="重点部位照片 (请上传1~9张照片)" name="keyPartsUrlList" label-width="100%">
                    <u-upload :fileList="form.keyPartsUrlList" @afterRead="(info) => afterReadFive(info, 'form', 45)"
                      @delete="(info) => deletePhoto(info, 'form')" name="keyPartsUrlList" :maxCount="9"
                      :multiple="true" width="100" height="80">
                      <image :src="baseImgUrl + 'upload-icon3.png'" style="width: 200rpx; height: 160rpx"></image>
                    </u-upload>
                  </uni-forms-item>
                </view>
                <view class="image-form-item-no-border">
                  <uni-forms-item label="风险点照片 (请上传1~9张照片)" name="riskPointsUrlList" label-width="100%">
                    <u-upload :fileList="form.riskPointsUrlList" @afterRead="(info) => afterReadFive(info, 'form', 46)"
                      @delete="(info) => deletePhoto(info, 'form')" name="riskPointsUrlList" :maxCount="9"
                      :multiple="true" width="100" height="80">
                      <image :src="baseImgUrl + 'upload-icon3.png'" style="width: 200rpx; height: 160rpx"></image>
                    </u-upload>
                  </uni-forms-item>
                </view>
              </view>
              <view class="content-inner-wrapper" v-show="active == 1">
                <view class="form-item-title">营业执照</view>
                <view class="image-form-item">
                  <uni-forms-item label="证件图片 (大小2M以内)" name="businessLicenseUrl" label-width="100%">
                    <u-upload :fileList="form.businessLicenseUrl" @afterRead="(info) => afterReadBusinessPhoto(info)"
                      @delete="(info) => deleteBusinessPhoto(info, 'form')" name="businessLicenseUrl" :maxCount="1"
                      width="100" height="80">
                      <image :src="baseImgUrl + 'upload-icon3.png'" style="width: 200rpx; height: 160rpx"></image>
                    </u-upload>
                  </uni-forms-item>
                </view>
                <uni-forms-item label="企业名称" name="businessName" key="businessName">
                  <view class="form-content-item">
                    <uni-easyinput type="text" v-model="form.businessName" disableColor="#ffffff" :inputBorder="false"
                      placeholder="请填写" :clearable="true" />
                  </view>
                </uni-forms-item>
                <uni-forms-item label="信用代码" name="creditCode" key="creditCode" style="border-bottom: 1px solid;">
                  <view class="form-content-item">
                    <uni-easyinput type="text" v-model="form.creditCode" disableColor="#ffffff" :inputBorder="false"
                      placeholder="请填写" :clearable="true" maxlength="22" />
                  </view>
                </uni-forms-item>
                <view style="border-top: 1rpx solid #E4E4E4"></view>
              </view>
              <view class="content-inner-wrapper" v-show="active == 2">
                <view class="form-item-title">法人/经营者信息</view>
                <uni-forms-item label="国籍" name="nationality1" required>
                  <view class="form-content-item" @click="hadleShowPicker('nationality', 'nationality1')">
                    <uni-easyinput type="text" :disabled=" true  " v-model="form.nationality1_text" disabled
                      disableColor="#ffffff" :inputBorder="false" placeholder="请选择" :clearable="true" />
                    <uni-icons type="right" size="21" color="#C2C0C0"></uni-icons>
                  </view>
                </uni-forms-item>
                <uni-forms-item label="证件类型" name="idType1" required>
                  <view class="form-content-item" @click="hadleShowPicker('certificate_type', 'idType1')">
                    <uni-easyinput type="text" v-model="form.idType1_text" disabled disableColor="#ffffff"
                      :inputBorder="false" placeholder="请选择" :clearable="true" />
                    <uni-icons type="right" size="21" color="#C2C0C0"></uni-icons>
                  </view>
                </uni-forms-item>
                <uni-forms-item label="证件号码" name="idCard" required key="idCard">
                  <view class="form-content-item">
                    <uni-easyinput :type="form.idType1 == 10 ? 'idcard' : 'text'" v-model="form.idCard"
                      disableColor="#ffffff" :inputBorder="false" placeholder="请填写" :clearable="true"
                      @blur="handleIdCardChangeLegal" :maxlength="18" />
                    <view class="scan-wrapper" slot="right" @click="handleCamera('legalPerson')">
                      <image src="/static/icons/scan.png" class="scan-img"></image>
                    </view>
                  </view>
                </uni-forms-item>
                <uni-forms-item label="姓名" name="legalPersonName" required key="legalPersonName">
                  <view class="form-content-item" :class="form.legalPersonName ?  '' : 'input-item'">
                    <uni-easyinput type="text" v-model="form.legalPersonName" disableColor="#ffffff"
                      :inputBorder="false" placeholder="请填写" :clearable="true" />
                  </view>
                </uni-forms-item>
                <uni-forms-item label="出生日期" name="birth1" required>
                  <view class="form-content-item" @click="handleShowDatetimePicker('birth1')">
                    <uni-easyinput type="text" v-model="form.birth1" disabled disableColor="#ffffff"
                      :inputBorder="false" placeholder="请选择" :clearable="true" />
                    <uni-icons type="right" size="21" color="#C2C0C0"></uni-icons>
                  </view>
                </uni-forms-item>
                <uni-forms-item label="性别" name="sex1" required>
                  <view class="form-content-item" @click="hadleShowPicker('sex_type', 'sex1')">
                    <uni-easyinput type="text" v-model="form.sex1_text" disabled disableColor="#ffffff"
                      :inputBorder="false" placeholder="请选择" :clearable="true" />
                    <uni-icons type="right" size="21" color="#C2C0C0"></uni-icons>
                  </view>
                </uni-forms-item>
                <uni-forms-item label="民族" name="nation1" required>
                  <view class="form-content-item" @click="hadleShowPicker('nation', 'nation1')">
                    <uni-easyinput type="text" v-model="form.nation1_text" disabled disableColor="#ffffff"
                      :inputBorder="false" placeholder="请选择" :clearable="true" />
                    <uni-icons type="right" size="21" color="#C2C0C0"></uni-icons>
                  </view>
                </uni-forms-item>
                <!-- <uni-forms-item label="户籍地址" name="residenceDetail1" required>
                  <view class="form-content-item" :class="form.residenceDetail1 ?  '' : 'input-item'">
                    <uni-easyinput type="text" v-model="form.residenceDetail1" disableColor="#ffffff"
                      :inputBorder="false" placeholder="请填写" :clearable="true" />
                  </view>
                </uni-forms-item>
                <uni-forms-item label="户籍地所属区县" name="residenceCode1" required>
                  <view class="form-content-item" @click="handleCityPicker('residenceCode1')">
                    <uni-easyinput type="text" v-model="form.residenceCode1_text" disabled disableColor="#ffffff"
                      :inputBorder="false" placeholder="请选择" :clearable="true" />
                    <uni-icons type="right" size="21" color="#C2C0C0"></uni-icons>
                  </view>
                </uni-forms-item>
                <view class="hint" style="font-size: 10px;color: #f56c6c;margin-top: -20rpx;padding-bottom: 10rpx;"
                  v-if="areaList.length">
                  户籍所属区县由系统自动匹配，如匹配不准确或未匹配到请务必手动修改!
                </view> -->
                <uni-forms-item label="手机号码" name="mobile" required key="mobile">
                  <view class="form-content-item" :class="form.mobile ?  '' : 'input-item'">
                    <uni-easyinput type="number" :maxlength="11" v-model="form.mobile" disableColor="#ffffff"
                      :inputBorder="false" placeholder="请填写" :clearable="true" />
                  </view>
                </uni-forms-item>
                <view style="border-top: 1rpx solid #E4E4E4"></view>
              </view>
              <view class="content-inner-wrapper" v-show="active == 3">
                <view class="form-item-title">负责人</view>
                <uni-forms-item label="国籍" name="nationality2" required>
                  <view class="form-content-item" @click="hadleShowPicker('nationality', 'nationality2')">
                    <uni-easyinput type="text" :disabled=" true  " v-model="form.nationality2_text" disabled
                      disableColor="#ffffff" :inputBorder="false" placeholder="请选择" :clearable="true" />
                    <uni-icons type="right" size="21" color="#C2C0C0"></uni-icons>
                  </view>
                </uni-forms-item>
                <uni-forms-item label="证件类型" name="idType2" required>
                  <view class="form-content-item" @click="hadleShowPicker('certificate_type', 'idType2')">
                    <uni-easyinput type="text" v-model="form.idType2_text" disabled disableColor="#ffffff"
                      :inputBorder="false" placeholder="请选择" :clearable="true" />
                    <uni-icons type="right" size="21" color="#C2C0C0"></uni-icons>
                  </view>
                </uni-forms-item>
                <uni-forms-item label="证件号码" name="fzidCard" required key="fzidCard">
                  <view class="form-content-item">
                    <uni-easyinput :type="form.idType2 == 10 ? 'idcard' : 'text'" :maxlength="18"
                      v-model="form.fzidCard" disableColor="#ffffff" :inputBorder="false" placeholder="请填写"
                      :clearable="false" disabled @blur="handleIdCardChangeDuty" />
                  </view>
                </uni-forms-item>
                <uni-forms-item label="姓名" name="dutyPersonName" required key="dutyPersonName">
                  <view class="form-content-item" :class="form.dutyPersonName ?  '' : 'input-item'">
                    <uni-easyinput type="text" v-model="form.dutyPersonName" disableColor="#ffffff" :inputBorder="false"
                      placeholder="请填写" :clearable="false" disabled />
                  </view>
                </uni-forms-item>
                <uni-forms-item label="出生日期" name="birth2" required>
                  <view class="form-content-item" @click="handleShowDatetimePicker('birth2')">
                    <uni-easyinput type="text" v-model="form.birth2" disabled disableColor="#ffffff"
                      :inputBorder="false" placeholder="请选择" :clearable="true" />
                    <uni-icons type="right" size="21" color="#C2C0C0"></uni-icons>
                  </view>
                </uni-forms-item>
                <uni-forms-item label="性别" name="sex2" required>
                  <view class="form-content-item" @click="hadleShowPicker('sex_type', 'sex2')">
                    <uni-easyinput type="text" v-model="form.sex2_text" disabled disableColor="#ffffff"
                      :inputBorder="false" placeholder="请选择" :clearable="true" />
                    <uni-icons type="right" size="21" color="#C2C0C0"></uni-icons>
                  </view>
                </uni-forms-item>
                <uni-forms-item label="民族" name="nation2" required>
                  <view class="form-content-item">
                    <uni-easyinput type="text" v-model="form.nation2_text" disabled disableColor="#ffffff"
                      :inputBorder="false" placeholder="请选择" :clearable="false" />
                    <uni-icons type="right" size="21" color="#C2C0C0"></uni-icons>
                  </view>
                </uni-forms-item>
                <!-- <uni-forms-item label="户籍地址" name="residenceDetail2" required>
                  <view class="form-content-item" :class="form.residenceDetail2 ?  '' : 'input-item'">
                    <uni-easyinput type="text" v-model="form.residenceDetail2" disableColor="#ffffff"
                      :inputBorder="false" placeholder="请填写" :clearable="false" disabled />
                  </view>
                </uni-forms-item>
                <uni-forms-item label="户籍地所属区县" name="residenceCode2" required>
                  <view class="form-content-item">
                    <uni-easyinput type="text" v-model="form.residenceCode2_text" disabled disableColor="#ffffff"
                      :inputBorder="false" placeholder="请选择" :clearable="false" />
                    <uni-icons type="right" size="21" color="#C2C0C0"></uni-icons>
                  </view>
                </uni-forms-item>
                <view class="hint" style="font-size: 10px;color: #f56c6c;margin-top: -20rpx;padding-bottom: 10rpx;"
                  v-if="areaList1.length">
                  户籍所属区县由系统自动匹配，如匹配不准确或未匹配到请务必手动修改!
                </view> -->
                <uni-forms-item label="手机号码" name="fzmobile" required key="fzmobile">
                  <view class="form-content-item" :class="form.fzmobile ?  '' : 'input-item'">
                    <uni-easyinput type="number" :maxlength="11" v-model="form.fzmobile" disableColor="#ffffff"
                      :inputBorder="false" placeholder="请填写" :clearable="false" disabled />
                  </view>
                </uni-forms-item>
                <view style="border-top: 1rpx solid #E4E4E4"></view>
              </view>
            </uni-forms>
          </view>
        </view>
        <view class="button-wrapper">
          <view class="next-btn" @click="handleNext" v-if="active == 0">下一步</view>
          <template v-else>
            <view class="cancel btn-item" @click="handlePrev">上一步
            </view>
            <view class="submit btn-item" @click="handleNext">{{ active === stepList.length - 1 ? "提交" : "下一步" }}
            </view>
          </template>
        </view>
      </view>
      <u-picker closeOnClickOverlay v-if="pickerShow" :show="pickerShow" :columns="pickerData" keyName="text"
        @confirm="onPickerConfirm" @cancel="pickerShow = false" @close="pickerShow = false"
        :defaultIndex="defaultIndex"></u-picker>

      <!-- <yy-city-picker :visible="cityPickerVisible" @confirm="onCityConfirm"
        @cancel="cityPickerVisible = false"></yy-city-picker> -->

      <yy-city-picker-all v-if="cityPickerVisible" :visible="cityPickerVisible" @confirm="onCityConfirm"
        @cancel="cityPickerVisible = false" :default-value="defaultCityCode"></yy-city-picker-all>

      <uni-data-picker style="width: 0;height: 0;display: block;overflow: hidden;" ref="dataPickerRef"
        placeholder="请选择行业分类" popup-title="请选择行业分类" :localdata="addressList"
        :map="{ text: 'informationName', value: 'id' }" @change="handleDataPickerChange">
      </uni-data-picker>
    </view>
    <yy-photo-mask :visible.sync="visibleCamera" :baseImgUrl="baseImgUrl" :clientId="clientId"
      :clientSecret="clientSecret" @parsedSuccess="onParsedSuccess"
      @generateFilePath="onGenerateFilePath"></yy-photo-mask>
    <lingfeng-timepicker ref="datetimePickerRef" type="date" :defaultData="defaultData" :minDate="minDate"
      :maxDate="maxDate" @change="timeChange"></lingfeng-timepicker>
  </view>
</template>
<script>
  import {
    AuthenticationDetail,
    findPolice
  } from '../../api/home';
  import {
    informationTree,
    messageSave
  } from '../../api/myself';
  import {
    wxMapkey
  } from '../../config';
  import pickerMixin from '../../utils/picker-mixin';
  import uploadFileMixin from '../../utils/upload-file-mixin';
  import {
    Toast,
    checkIDCard,
    checkSocialCardNumber,
    errorToast,
    getBase64Two,
    getLocation,
    getposition,
    idCardRule,
    isLoading,
    medicalTreatment,
    navBack,
    parseIDCard,
    phoneRule,
    regPhone,
    registerNumber,
    requireInputRule,
    selectNation,
    setDefaultProvinceCode,
    uniTrim,
    uploadFile,
    useNetWork
  } from '../../utils/util';

  import lodash from '@/utils/lodash.js'
  import moment from '@/utils/moment.js'

  const chooseLocation = requirePlugin("chooseLocation");

  export default {
    mixins: [uploadFileMixin, pickerMixin],
    data() {
      return {
        clientId: this.$clientId,
        clientSecret: this.$clientSecret,
        baseImgUrl: this.$baseImgUrl,
        active: 0,
        stepList: [{
            text: "基本信息",
          },
          {
            text: "资质信息 ",
          },
          {
            text: "法人/经营者信息",
          },
          {
            text: "负责人信息",
          },
        ],
        formRef: null,
        formRef2: null,
        formRef3: null,
        formRef4: null,
        form: {
          industryInformationId: '',
          industryInformationId_text: '',
          companyName: '',
          lng: '',
          lat: '',
          lnglat_text: '',
          policeAgencyId: '',
          policeAgencyName: '',
          standardAddress: '',
          openingTime: '', // 营业时间

          doorheadUrlList: [], // 场所门头照
          interiorUrlList: [], // 场所内部照片

          keyPartsUrlList: [], // 重点部位照片
          riskPointsUrlList: [], // 风险点照片

          // 资质信息
          businessLicenseUrl: [], // 营业执照
          businessName: '',
          creditCode: '',

          // 法人信息
          personImage: '', // 法人身份证
          idCard: '',
          legalPersonName: '',
          mobile: '',
          nation1: '',

          nationality1: 'CHN',
          nationality1_text: '中国',
          idType1: '10',
          idType1_text: '身份证',
          birth1: '',
          sex1: '',
          // residenceDetail1: '', // 户籍地址
          // residenceCode1: '', // 户籍编码
          // residenceCode1_text: '',
          // 负责人信息
          fzpersonImage: '', // 负责人身份证
          fzidCard: '',
          dutyPersonName: '',
          fzmobile: '',
          nation2: '',
          nationality2: 'CHN',
          nationality2_text: '中国',
          idType2: '10',
          idType2_text: '身份证',
          birth2: '',
          sex2: '',
          // residenceDetail2: '', // 户籍地址
          // residenceCode2: '', // 户籍编码
          // residenceCode2_text: '',
        },
        dataPickerRef: null,
        addressList: [],
        scalPersonType: '',
        visibleCamera: false,
        userInfo: uni.getStorageSync('user'),
        options: {},
        // 户籍地址
        cityPickerVisible: false,
        cityPickerWithKey: '',

        areaList: [],
        defaultCityCode: '',
        defaultCityCodeLegal: '',
        defaultCityCodeDuty: '',
        areaList1: [],
        // 日期相关的
        defaultData: {
          startTime: moment(new Date()).format('YYYY-MM-DD')
        },
        minDate: {
          year: 1800,
          month: 1,
          date: 1
        },
        maxDate: {
          year: new Date().getFullYear(),
          month: new Date().getMonth() + 1,
          date: new Date().getDate()
        },
        datetimePickerRef: null,
        dateTimeCelltype: ''
      }
    },
    watch: {
      // 经纬度发生变化的时候获取最新的 派出所信息
      'form.lnglat_text': function(newVal) {
        let lnglat = newVal.split('-')
        let location = {
          longitude: lnglat[0],
          latitude: lnglat[1]
        }
        this.getPoliceInfo(location);
      },
      'active': function(newVal) {
        if (newVal == 2 && this.defaultCityCodeLegal) {
          this.defaultCityCode = this.defaultCityCodeLegal
        } else if (newVal == 3 && this.defaultCityCodeDuty) {
          this.defaultCityCode = this.defaultCityCodeDuty
        }
      }
    },
    onReady() {},
    onShow() {
      uni.$on("leadPoliceStation", (v) => {
        let {
          policeAgencyName,
          id
        } = v[0];
        this.$set(this.form, "policeAgencyId", id);
        this.$set(this.form, "policeAgencyName", policeAgencyName);
      });

      // 选择标准地址
      uni.$on("selectedDetailAddress", (detailAddress) => {
        let {
          jlxFDzbm,
          jzFDzbm,
          dyFDzbm,
          lcFDzbm,
          fzFDzbm,
          roomName,
          buildType
        } =
        detailAddress;
        this.$set(this.form, "fSsjlxxqDzbm", jlxFDzbm);
        this.$set(this.form, "fSsjzwDzbm", jzFDzbm);
        this.$set(this.form, "fSsdyDzbm", dyFDzbm);
        this.$set(this.form, "fSslcDzbm", lcFDzbm);
        this.$set(this.form, "fSsjzwdyfwDzbm", fzFDzbm);
        this.$set(this.form, "standardAddress", roomName);
        this.$set(this.form, "buildType", buildType + '');
      });

      // 设置选择经纬度的值
      const location = chooseLocation.getLocation(); // 如果点击确认选点按钮，则返回选点结果对象，否则返回null
      // 并且当前操作的是 经纬度
      if (location) {
        // 如果用户有选择经纬度，则需要进行更新 ，并且要获取最新的派出所信息
        // this.$set(this.form, 'addressDetail', location.address + location.name)
        this.form.lnglat_text = `${location.longitude}-${location.latitude}`;
        this.form.lng = location.longitude;
        this.form.lat = location.latitude;
      }
    },
    async onLoad(options) {
      this.options = options
      // 新增
      uni.showLoading({
        title: '正在获取当前位置信息，请稍等！'
      })
      try {
        let rp = await getLocation()
        this.form.lng = parseFloat(rp.longitude.toFixed(6));
        this.form.lat = parseFloat(rp.latitude.toFixed(6));
        this.form.lnglat_text = `${this.form.lng}-${this.form.lat}`;
      } catch (e) {
        //TODO handle the exception
      } finally {
        uni.hideLoading()
      }

      // 获取行业树
      informationTree().then((res) => {
        if (res.code == 200) {
          this.addressList = res.result || [];
        }
      });
      // 默认填写负责人信息
      this.getAuthenticationDetail()
    },
    onUnload() {
      chooseLocation.setLocation(null);
      uni.$off('selectedDetailAddress')
      uni.$off('leadPoliceStation')
    },
    methods: {
      handleIdCardChangeLegal() {
        let params = {
          idCard: this.form.idCard,
          fDzbm: this.form.fSsjzwDzbm
        }
        if (this.form.idType1 == 10) {
          this.setBirthdayAdnSex(this.form.idCard, 'legal')
          setDefaultProvinceCode.call(this, params, ({
            code,
            address
          }) => {
            this.defaultCityCode = code
            this.defaultCityCodeLegal = code
          })
        }
      },
      handleIdCardChangeDuty() {
        let params = {
          idCard: this.form.fzidCard,
          fDzbm: this.form.fSsjzwDzbm
        }
        if (this.form.idType2 == 10) {
          this.setBirthdayAdnSex(this.form.fzidCard, 'duty')
          setDefaultProvinceCode.call(this, params, ({
            code,
            address
          }) => {
            this.defaultCityCodeDuty = code
            this.defaultCityCode = code
          })
        }
      },
      moment,
      async handleNext() {
        // 当等于 length -1 的时候就 进行提交
        // 表单分步 校验
        const allForm = {
          ...this.form,
        }
        let {
          dutyPersonName,
          fzidCard,
          fzpersonImage,
          fzmobile,
          companyName,
          businessName,
          creditCode,
          industryInformationId,
          policeAgencyId,
          doorheadUrlList,
          interiorUrlList,
          keyPartsUrlList,
          riskPointsUrlList,
          standardAddress,
          openingTime,
          lat,
          lng,
          businessLicenseUrl,
          personImage,
          legalPersonName,
          idCard,
          residenceDetail,
          mobile,
          mobileCode,
          fSsjlxxqDzbm, // 选择街路巷
          fSsjzwDzbm, // 选择建筑物
          fSsdyDzbm, // 选择单元
          fSslcDzbm, // 选择楼层
          fSsjzwdyfwDzbm, // 选择房屋
          nation1,

          nationality1,
          idType1,
          birth1,
          sex1,
          // residenceDetail1, // 户籍地址
          // residenceCode1, // 户籍编码

          nation2,
          nationality2,
          idType2,
          birth2,
          sex2,
          // residenceDetail2, // 户籍地址
          // residenceCode2 // 户籍编码
        } = allForm;

        if (this.active == 0) {
          if (!industryInformationId) {
            Toast("请选择行业分类！");
            return;
          }
          if (!companyName || !uniTrim(companyName)) {
            Toast("请输入场所名称！");
            return;
          }
          if (!openingTime) {
            Toast('请选择开业时间！')
            return
          }
          let companyRegular = /^[a-zA-Z\u4e00-\u9fa5]+$/;
          if (!companyRegular.test(companyName)) {
            Toast("请输入正确的场所名称！");
            return;
          }

          if (!lng) {
            Toast("请选择经纬度！");
            return;
          }
          if (!policeAgencyId) {
            Toast("请选择所属派出所！");
            return;
          }

          if (!standardAddress) {
            Toast("请选择关联标准地址！");
            return;
          }

          if (!doorheadUrlList.length) {
            Toast("请上传场所门头照片！");
            return;
          }

          if (!interiorUrlList.length) {
            Toast("请上传场所内部照片！");
            return;
          }
          this.active++
          return
        }

        if (this.active == 1) {

          // if (!businessName || !uniTrim(businessName)) {
          //   Toast("请输入企业名称！");
          //   return;
          // }

          // if (!creditCode || !uniTrim(creditCode)) {
          //   Toast("请输入信用代码！");
          //   return;
          // }

          // if (!checkSocialCardNumber(creditCode)) {
          //   Toast("请输入正确的信用代码！");
          //   return;
          // }

          // let check = checkSocialCardNumber(creditCode);
          // let medical = medicalTreatment(creditCode);
          // let refisNum = registerNumber(creditCode);
          // if (!check && !medical && !refisNum) {
          //   Toast("请输入正确的信用代码！");
          //   return;
          // }
          this.active++
          return
        }
        if (this.active == 2) {
          if (!nationality1) {
            Toast('请选择国籍！')
            return
          }
          if (!idType1) {
            Toast('请选择证件类型！')
            return
          }

          if (!idCard || !uniTrim(idCard)) {
            Toast("请输入证件号码！");
            return;
          }

          let idCardFlag = checkIDCard(this.form.idCard);
          if (!idCardFlag && idType1 == 10) {
            Toast("请输入正确的证件号码！");
            return;
          }

          if (!legalPersonName || !uniTrim(legalPersonName)) {
            Toast("请输入姓名！");
            return;
          }

          let legalPersonRegexp =
            /^[\u2000-\u206f\u3000-\u303f\u4e00-\u9fef\uff00-\uffef]*$/;
          if (!legalPersonRegexp.test(legalPersonName)) {
            Toast("姓名只能输入汉字！");
            return;
          }
          if (!birth1) {
            Toast('请选择出生日期！')
            return
          }
          if (!sex1) {
            Toast('请选择性别！')
            return
          }

          if (!nation1) {
            Toast('请选择民族！')
            return
          }
          // if (!residenceDetail1 || !uniTrim(residenceDetail1)) {
          //   Toast('请填写户籍地址！')
          //   return
          // }
          // if (!residenceCode1) {
          //   Toast('请选择户籍所属区县！')
          //   return
          // }

          if (!mobile) {
            Toast("请输入手机号码！");
            return;
          }

          if (mobile && !this.$u.test.mobile(mobile)) {
            Toast("请输入正确的手机号！");
            return;
          }
          this.active++
          return
        }
        if (this.active === 3) {
          if (!nationality2) {
            Toast('请选择国籍！')
            return
          }
          if (!idType2) {
            Toast('请选择证件类型！')
            return
          }

          if (!fzidCard || !uniTrim(fzidCard)) {
            Toast("请输入证件号码！");
            return;
          }

          let idCardFlag = checkIDCard(this.form.fzidCard);
          if (!idCardFlag && idType2 == 10) {
            Toast("请输入正确的证件号码！");
            return;
          }
          // 验证功能
          if (!dutyPersonName || !uniTrim(dutyPersonName)) {
            Toast("请输入姓名！");
            return;
          }
          if (!birth2) {
            Toast('请选择出生日期！')
            return
          }
          if (!sex2) {
            Toast('请选择性别！')
            return
          }

          if (!nation2) {
            Toast('请选择民族！')
            return
          }
          // if (!residenceDetail2 || !uniTrim(residenceDetail2)) {
          //   Toast('请填写户籍地址！')
          //   return
          // }
          // if (!residenceCode2) {
          //   Toast('请选择户籍所属区县！')
          //   return
          // }

          let legalPersonRegexp =
            /^[\u2000-\u206f\u3000-\u303f\u4e00-\u9fef\uff00-\uffef]*$/;
          if (!legalPersonRegexp.test(dutyPersonName)) {
            Toast("姓名只能输入汉字！");
            return;
          }

          if (!fzmobile) {
            Toast("请输入手机号码！");
            return;
          }

          if (fzmobile && !this.$u.test.mobile(fzmobile)) {
            Toast("请输入正确的手机号！");
            return;
          }

          let dataAll = {
            companyMessageInfo: {
              companyName: companyName,
              businessName: businessName || null,
              creditCode: creditCode || null,
              industryInformationId: industryInformationId,
              policeAgencyId: policeAgencyId,
              businessLicenseUrl: businessLicenseUrl.map(item => item.halfPath).join() ? businessLicenseUrl
                .map(
                  item => item.halfPath).join() : null,
              doorheadUrlList: doorheadUrlList.map(item => item.halfPath),
              interiorUrlList: interiorUrlList.map(item => item.halfPath),
              keyPartsUrlList: keyPartsUrlList.map(item => item.halfPath),
              riskPointsUrlList: riskPointsUrlList.map(item => item.halfPath),
              id: this.options.id || "",
              lng,
              lat,
              fSsjlxxqDzbm: fSsjlxxqDzbm,
              fSsjzwDzbm: fSsjzwDzbm,
              fSsdyDzbm: fSsdyDzbm,
              fSslcDzbm: fSslcDzbm,
              fSsjzwdyfwDzbm: fSsjzwdyfwDzbm,
              buildType: this.form.buildType,
              openingTime: moment(openingTime).format('YYYY/MM/DD')
            },
            companyLegalPersonInfo: {
              personImage: personImage || "",
              legalPersonName: legalPersonName,
              idCard: idCard,
              mobile: mobile,
              nation: nation1,
              nationality: nationality1,
              idType: idType1,
              birth: birth1,
              sex: sex1,
              // residenceDetail: residenceDetail1, // 户籍地址
              // residenceCode: residenceCode1, // 户籍编码
            },
            companyDutyPersonInfo: {
              dutyPersonName: dutyPersonName,
              idCard: fzidCard,
              mobile: fzmobile,
              personImage: fzpersonImage,
              nation: nation2,
              nationality: nationality2,
              idType: idType2,
              birth: birth2,
              sex: sex2,
              // residenceDetail: residenceDetail2, // 户籍地址
              // residenceCode: residenceCode2 // 户籍编码
            },
            mobileCode: mobileCode,
          };
          isLoading(true)
          messageSave(dataAll).then((res) => {
              if (res.code == 200) {
                Toast("添加企业成功");
                uni.$emit("actual_enterprises_addBusiness");
                setTimeout(() => {
                  navBack("back", this.options.backIndex);
                }, 200)
                return;
              }
              Toast(res.message);
            })
            .finally(() => {
              isLoading(false)
            })
        }
      },
      handlePrev() {
        this.active--
      },
      handleSelectIndustry() {
        this.$refs.dataPickerRef.show()
      },
      handleDataPickerChange(e) {
        // 给 text 和 value 赋值
        let value = lodash.get(e, 'detail.value', [])
        if (value.length) {
          // 取最后一个的值作为 value 
          // 合并 text 展示
          let id = value[value.length - 1].value

          this.form.industryInformationId = id
          let text = value.map((item) => {
            return item.text
          }).join('/')
          this.form.industryInformationId_text = text
        }
        this.$refs.dataPickerRef.hide()
      },
      policeAgencyFoces() {
        if (!this.form.lng) {
          Toast("请先选择经纬度");
          return;
        }
        uni.navigateTo({
          url: `/leadReporting/leadReporting/leadPoliceStation?lng=${this.form.lng}&lat=${this.form.lat}`,
        });
      },
      mapHandle() {
        const key = wxMapkey;
        const referer = "场所信息管理企业端"; //调用插件的app的名称
        const location = JSON.stringify({
          latitude: this.form.lat,
          longitude: this.form.lng,
        });
        const category = "生活服务,娱乐休闲";

        wx.navigateTo({
          url: "plugin://chooseLocation/index?key=" +
            key +
            "&referer=" +
            referer +
            "&location=" +
            location +
            "&category=" +
            category
        });
      },
      handleCamera(personType) {
        this.scalPersonType = personType
        this.visibleCamera = true
      },
      onParsedSuccess({
        userName,
        idcard,
        domicileAddress,
        nation
      }) {
        let nationOption = selectNation(this.dictMapping, nation)
        if (this.scalPersonType === 'legalPerson') {
          this.$set(this.form, 'legalPersonName', userName)
          this.$set(this.form, 'idCard', idcard)
          // this.$set(this.form, 'residenceDetail1', domicileAddress)
          this.handleIdCardChangeLegal()
          if (nationOption) {
            this.form.nation1 = nationOption.value
            this.form.nation1_text = nationOption.text
          }
        } else if (this.scalPersonType === 'responsiblePerson') {
          this.$set(this.form, 'dutyPersonName', userName)
          this.$set(this.form, 'fzidCard', idcard)
          // this.$set(this.form, 'residenceDetail2', domicileAddress)
          this.handleIdCardChangeDuty()
          if (nationOption) {
            this.form.nation2 = nationOption.value
            this.form.nation2_text = nationOption.text
          }
        }
      },
      onGenerateFilePath(file) {
        uploadFile({
            url: "/web/sys/upload/upload_file",
            filePath: file,
            name: "file",
            formData: {
              type: 20,
            },
          })
          .then((res) => {
            let {
              fullPath,
              halfPath
            } = res.result;
            isLoading(false);
            if (this.scalPersonType == "legalPerson") {
              // 法人身份证
              this.form.personImage = halfPath;
            }
            if (this.scalPersonType == "responsiblePerson") {
              // 负责人身份证
              this.form.fzpersonImage = halfPath;
            }
          })
          .finally(() => {
            isLoading(false);
          })
      },
      async getDetailAddress() {
        if (!this.form.lng) {
          Toast("请选择经纬度！");
          return;
        }
        if (!this.form.policeAgencyName) {
          Toast("请选择所属派出所！");
          return;
        }
        uni.navigateTo({
          url: `/leadReporting/detailAddress/detailAddress?houseLng=${this.form.lng}&houseLat=${this.form.lat}&policeAgencyId=${this.form.policeAgencyId}`,
        });
      },
      deleteBusinessPhoto(event) {
        // 并且清空图片地址
        this.form.businessLicenseUrl.splice(event.index, 1)
      },
      // 营业执照
      afterReadBusinessPhoto(info) {
        // 上传营业执照图片
        this.uploadImage(info.file.url, 2);
        uni.request({
          url: "https://aip.baidubce.com/oauth/2.0/token",
          method: "GET",
          data: {
            grant_type: "client_credentials",
            client_id: this.clientId,
            client_secret: this.clientSecret,
          },
          success: (res) => {
            this.base64Business(res.data.access_token, info);
          },
        });
      },
      base64Business(token, info) {
        getBase64Two(info.file.url)
          .then((res) => {
            return res;
          })
          .then((res) => {
            uni.request({
              url: `https://aip.baidubce.com/rest/2.0/ocr/v1/business_license?access_token=${token}`,
              method: "POST",
              header: {
                "Content-Type": "application/x-www-form-urlencoded",
              },
              data: {
                id_card_side: "front",
                image: res,
              },
              success: (resbai) => {
                let {
                  statusCode,
                  data
                } = resbai;

                if (statusCode == 200 && data.words_result && data.words_result["单位名称"]) {
                  this.$set(
                    this.form,
                    "businessName",
                    data.words_result.单位名称.words
                  );
                  this.$set(
                    this.form,
                    "creditCode",
                    data.words_result.社会信用代码.words
                  );
                  return;
                }
              },
            });
          });
      },
      uploadImage(fileurl, type, flagName) {
        isLoading(true);
        uploadFile({
            url: "/web/sys/upload/upload_file",
            filePath: fileurl,
            name: "file",
            formData: {
              type: type,
            }
          })
          .then((res) => {
            isLoading(false);
            let {
              fullPath,
              halfPath
            } = res.result;

            if (type == 2) {
              // 营业执照的
              this.form.businessLicenseUrl.push({
                url: fullPath,
                halfPath: halfPath,
              });
              uni.hideLoading();
            }
          })
          .finally(() => {
            isLoading(false);
          })
      },
      async getPoliceInfo(longlat) {
        let params = {
          lng: longlat.longitude,
          lat: longlat.latitude,
          pageNo: 1,
          pageSize: 50,
        };
        let res = await findPolice(params)
        let currentPoliceList = [];
        currentPoliceList = res.result.records

        // 取返回的第一个
        if (currentPoliceList.length) {
          const {
            id,
            name
          } = currentPoliceList[0];
          this.$set(this.form, "policeAgencyId", id);
          this.$set(this.form, "policeAgencyName", name);
        }
      },
      handleCityPicker(key) {
        this.cityPickerWithKey = key
        this.cityPickerVisible = true
      },
      // 确认
      onCityConfirm(event) {
        let key = this.cityPickerWithKey
        this.form[`${key}_text`] = event.address;
        this.form[`${key}`] = event.code;
        this.cityPickerVisible = false;
      },
      getAuthenticationDetail() {
        AuthenticationDetail().then((res) => {
          if (res.code == 200) {
            // 取出三个字段给其命名
            const {
              userName,
              mobile,
              idcard,
              nation,
              nationName,
              domicileAddress,
              residenceCode,
              residenceCodeName,
              idCardImage // 身份证照片
            } = res.result;
            this.$set(this.form, "dutyPersonName", userName);
            this.$set(this.form, "fzmobile", mobile);
            this.$set(this.form, "fzidCard", idcard);
            this.$set(this.form, "nation2", nation);
            this.$set(this.form, "nation2_text", nationName);
            // this.$set(this.form, "residenceDetail2", domicileAddress);
            // this.$set(this.form, "residenceCode2", residenceCode);
            // this.$set(this.form, "residenceCode2_text", residenceCodeName);
            // 把负责人的图片传过去
            if (idCardImage !== 'null' && idCardImage) {
              this.$set(this.form, "fzpersonImage", idCardImage);
            }
            // 设置性别和出生日期
            this.setBirthdayAdnSex(idcard, 'duty')
          }
        });
      },
      handleShowDatetimePicker(type) {
        this.dateTimeCelltype = type
        this.$refs.datetimePickerRef.show()
      },
      timeChange(val) {
        // 根据 celltype 进行判断
        if (this.dateTimeCelltype == 'birth1') {
          this.form.birth1 = moment(val).format('YYYY/MM/DD')
        } else if (this.dateTimeCelltype == 'birth2') {
          this.form.birth2 = moment(val).format('YYYY/MM/DD')
        }
      },
      setBirthdayAdnSex(idCard, personType) {
        const {
          birthDate,
          gender
        } = parseIDCard(idCard)
        if (personType == 'legal') {
          this.form.birth1 = moment(birthDate).format("YYYY/MM/DD")
          this.form.sex1 = gender == '男' ? '1' : '2'
          this.form.sex1_text = gender
        } else {
          this.form.birth2 = moment(birthDate).format("YYYY/MM/DD")
          this.form.sex2 = gender == '男' ? '1' : '2'
          this.form.sex2_text = gender
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import '../../styles/uni-form.scss';

  .root {
    width: 100%;
    height: 100%;
    position: relative;
    background: #F9F9F9;

    .root-inner {
      width: 100%;
      height: 100%;
    }

    .bg-top {
      width: 100%;
      position: absolute;
      left: 0;
      top: 0;
      height: 283rpx;
      background: #2488F5;
      border-radius: 0rpx 0rpx 0rpx 0rpx;
    }

    .container-wrapper {
      display: flex;
      flex-direction: column;
      width: 100%;
      height: 100%;
      position: relative;
      z-index: 10;

      .container-inner {
        flex: 1;
        height: 0;
        margin: 20rpx 16rpx 11rpx 16rpx;
        background: #FFFFFF;
        border-radius: 16rpx 16rpx 16rpx 16rpx;

        .form-style-wrapper {
          width: 100%;
          height: 100%;
          overflow: auto;
        }

        .content-inner-wrapper {
          .form-item-title {
            font-weight: bold;
            font-size: 30rpx;
            color: #000000;
            padding: 51rpx 0 22rpx 17rpx;
          }
        }
      }

      .button-wrapper {
        height: 120rpx;
        background: #ffffff;
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 100%;
        z-index: 10;
        padding: 0 35rpx;

        .next-btn {
          width: 680rpx;
          height: 88rpx;
          background: #2488F5;
          border-radius: 44rpx 44rpx 44rpx 44rpx;
          border: 1rpx solid #ACCBEC;
          text-align: center;
          font-weight: 500;
          font-size: 36rpx;
          color: #F9F9F9;
        }

        .btn-item {
          width: 324rpx;
          height: 88rpx;
          border-radius: 44rpx 44rpx 44rpx 44rpx;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .cancel {
          background: #ebebeb;
        }

        .submit {
          background: #2488f5;
          color: #fff;
        }
      }

      .map-img {
        color: #2488f5;
        font-size: 30rpx;
        font-weight: 500;

        image {
          display: inline-block;
          margin-right: 10rpx;
          vertical-align: top;
          width: 30rpx;
          height: 40rpx;
        }
      }

      .scan-wrapper {
        padding: 10rpx;

        .scan-img {
          width: 30rpx;
          height: 27.73rpx;
        }
      }
    }
  }
</style>